package com.entor.util;

import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

/**
 * 自动生成Dao/service/controller
 * @author HQJ
 * @version V1.0, 2016年11月18日
 * @since 2016年11月18日
 */
@SuppressWarnings("rawtypes")
public class AutoCreateServiceAndController {
	private static final String BEAN_URL = "com.entor.model";// entity路径
	private static final String DAO_URL = "com.entor.dao";// entity路径
	private static final String ACTION_URL = "com.entor.controller";// action路径
	private static final String SERVICE_URL = "com.entor.sevice";// service路径
	private static final String BASE_DAO_NAME = "BaseDao";//
	private static final String BASE_SERVICE_NAME = "BaseServiceI";//
	private static final String BASE_ACTION_NAME = "BaseController";//

	//
	private static final String FILTER_NAME = "\\w+\\.java";// 
	private static final boolean PRINT_INFO_FLAG = true;// 成功标志
	private static final boolean PRINT_ERROR_FLAG = true;// 失败标志
	private static final boolean FORCE_FLAG = false;// 
	private static final String RT_1 = "\r\n";// 一个格式符
	private static final String RT_2 = RT_1 + RT_1;// 
	private static final String BLANK_4 = " ";//TAB
	private static final String BLANK_8 = BLANK_4 + BLANK_4;

	private static final String DATE_STRING = new SimpleDateFormat(
			"yyyy年MM月dd日").format(new Date());

	// 
	private static final String ANNOTATION_AUTHOR_PARAMTER = "@author ";
	private static final String ANNOTATION_AUTHOR_NAME = "HQJ";
	private static final String ANNOTATION_AUTHOR = ANNOTATION_AUTHOR_PARAMTER
			+ ANNOTATION_AUTHOR_NAME;
	private static final String ANNOTATION_DATE = "@date ";
	private static final String ANNOTATION = "/**" + RT_1 + " * "
			+ ANNOTATION_AUTHOR + RT_1 + " * " + ANNOTATION_DATE + DATE_STRING
			+ RT_1 + " */" + RT_1;

	public static void main(String[] args) {
		String fileName = System.getProperty("user.dir") + "/src/"
				+ BEAN_URL.replace(".", "/");
		File file = new File(fileName);
		beanScan(file, "", true);
	}

	/**
	 * bean扫描
	 * @param file 文件保存路径
	 * @param parentPack
	 */
	public static void beanScan(File file, String parentPack, boolean isFirst) {
		if (file.exists()) {
			if (file.isDirectory()) {
				File[] fs = file.listFiles();
				for (int i = 0; i < fs.length; i++) {
					File f = fs[i];
					if(f.getName().contains("IdEntity.java")){
						continue;
					}
					String parent = "";
					if (!isFirst) {
						parent = parentPack + "." + file.getName();
					}
					beanScan(f, parent, false);
				}
			} else if (file.isFile() && file.getName().matches(FILTER_NAME)) {
				try {
					createByBean(file, parentPack);
				} catch (Exception e) {
					printError(file.getAbsolutePath(), e);
				}
			}
		}
	}

	public static void createByBean(File f, String parentPack) throws Exception {
		Class c = Class.forName(BEAN_URL + parentPack + "."
				+ f.getName().substring(0, f.getName().indexOf(".")));
		createBeanDao(c, parentPack);
		createBeanService(c, parentPack);
		createBeanServiceImpl(c, parentPack);
		createBeanController(c, parentPack);

	}

	public static void createBeanController(Class c, String parentPack)
			throws Exception {
		String cName = c.getSimpleName();
		String fileName = System.getProperty("user.dir") + "/src/"
				+ ACTION_URL.replace(".", "/") + parentPack.replace(".", "/")
				+ "/" + cName + "Controller.java";
		File f = new File(fileName);
		if (!f.isFile() || FORCE_FLAG) {
			File pf = f.getParentFile();
			if (!pf.isDirectory()) {
				pf.mkdirs();
			}
			StringBuffer sb = new StringBuffer();
			sb.append("package " + ACTION_URL + parentPack + ";" + RT_2);
			sb.append("import " + c.getName() + ";" + RT_1);//
			sb.append("import org.springframework.web.bind.annotation.RequestMapping;"
					+ RT_1);
			sb.append("import org.springframework.stereotype.Controller;"
					+ RT_1);
			sb.append("import org.springframework.beans.factory.annotation.Autowired;"
					+ RT_1);
			sb.append("import javax.servlet.http.HttpServletRequest;"
					+ RT_1);
			sb.append("import java.util.List;"
					+ RT_1);
			sb.append("import com.entor.util.Json;"
					+ RT_1);
			sb.append("import " + SERVICE_URL + parentPack + "." + cName
					+ "ServiceI;" + RT_1);
			sb.append(RT_2 + ANNOTATION);
			sb.append(RT_1 + "@RequestMapping(\"/" + cName.toLowerCase() + "\")");
			sb.append(RT_1 + "@Controller" + RT_1);
			sb.append("public class " + cName + "Controller ");
			sb.append("extends " + BASE_ACTION_NAME + "<" + cName + "> ");
			sb.append("{" + RT_2);
			sb.append(RT_1 + BLANK_4 + "@Autowired");
			sb.append(RT_1 + BLANK_4 + "private " + cName
					+ "ServiceI service;");
			sb.append(RT_1 + BLANK_8 + "");
			sb.append(RT_1 + BLANK_4 + "");
			//
			sb.append(RT_1+BLANK_4+"public List<"+cName+"> find("+cName+" "+cName.toLowerCase()+"){");
			sb.append(RT_1+BLANK_8+"List<"+cName+"> list = service.find("+cName.toLowerCase()+");");
			sb.append(RT_1+BLANK_8+"return list;");
			sb.append(RT_1 +BLANK_4+ "}");
			
			//
			sb.append(RT_1+BLANK_4+"public Json insert("+cName+" "+cName.toLowerCase()+"){");
			sb.append(RT_1+BLANK_8+"int i = service.insert("+cName.toLowerCase()+");");
			sb.append(RT_1+BLANK_8+"return this.getJson(i, \"保存\");");
			sb.append(RT_1 +BLANK_4+ "}");
			
			//
			sb.append(RT_1+BLANK_4+"public Json update("+cName+" "+cName.toLowerCase()+"){");
			sb.append(RT_1+BLANK_8+"int i = service.update("+cName.toLowerCase()+");");
			sb.append(RT_1+BLANK_8+"return this.getJson(i, \"更新\");");
			sb.append(RT_1 +BLANK_4+ "}");
			
			//
			sb.append(RT_1+BLANK_4+"public Json delete(HttpServletRequest request){");
			sb.append(RT_1+BLANK_8+"String id = request.getParameter(\"id\");");
			sb.append(RT_1+BLANK_8+"int i = service.delete(id);");
			sb.append(RT_1+BLANK_8+"return this.getJson(i, \"删除\");");
			sb.append(RT_1 +BLANK_4+ "}");
			
			sb.append(RT_2 + "}");
			FileWriter fw = new FileWriter(f, false);
			fw.write(sb.toString());
			fw.flush();
			fw.close();
			printLog(fileName);
		}
	}
	
	public static void createBeanDao(Class c, String parentPack)
			throws Exception {
		String cName = c.getSimpleName();
		String fileName = System.getProperty("user.dir") + "/src/"
				+ DAO_URL.replace(".", "/") + parentPack.replace(".", "/")
				+ "/" + cName + "Dao.java";
		File f = new File(fileName);
		if (!f.isFile() || FORCE_FLAG) {
			File pf = f.getParentFile();
			if (!pf.isDirectory()) {
				pf.mkdirs();
			}
			StringBuffer sb = new StringBuffer();
			sb.append("package " + DAO_URL + parentPack + ";" + RT_2);
			sb.append("import " + c.getName() + ";" + RT_1);// 导入实体包
			sb.append(RT_2 + ANNOTATION);
			sb.append("public interface " + cName + "Dao ");
			sb.append("extends " + BASE_DAO_NAME + "<" + cName + "> {");
			sb.append(RT_2 + "}");
			FileWriter fw = new FileWriter(f, false);
			fw.write(sb.toString());
			fw.flush();
			fw.close();
			printLog(fileName);
		}
	}

	public static void createBeanService(Class c, String parentPack)
			throws Exception {
		String cName = c.getSimpleName();
		String fileName = System.getProperty("user.dir") + "/src/"
				+ SERVICE_URL.replace(".", "/") + parentPack.replace(".", "/")
				+ "/" + cName + "ServiceI.java";
		File f = new File(fileName);
		if (!f.isFile() || FORCE_FLAG) {
			File pf = f.getParentFile();
			if (!pf.isDirectory()) {
				pf.mkdirs();
			}
			StringBuffer sb = new StringBuffer();
			sb.append("package " + SERVICE_URL + parentPack + ";" + RT_2);
			sb.append("import " + c.getName() + ";" + RT_1);// 导入实体包
			sb.append(RT_2 + ANNOTATION);
			sb.append("public interface " + cName + "ServiceI ");
			sb.append("extends " + BASE_SERVICE_NAME + "<" + cName + "> {");
			sb.append(RT_2 + "}");
			FileWriter fw = new FileWriter(f, false);
			fw.write(sb.toString());
			fw.flush();
			fw.close();
			printLog(fileName);
		}
	}

	public static void createBeanServiceImpl(Class c, String parentPack)
			throws Exception {
		String cName = c.getSimpleName();
		String fileName = System.getProperty("user.dir") + "/src/"
				+ SERVICE_URL.replace(".", "/") + parentPack.replace(".", "/")
				+ "/impl/" + cName + "ServiceImpl.java";
		File f = new File(fileName);
		if (!f.isFile() || FORCE_FLAG) {
			File pf = f.getParentFile();
			if (!pf.isDirectory()) {
				pf.mkdirs();
			}
			StringBuffer sb = new StringBuffer();
			sb.append("package " + SERVICE_URL + parentPack + ".impl;" + RT_2);
			sb.append("import org.springframework.stereotype.Service;" + RT_1);
			sb.append("import " + c.getName() + ";" + RT_1);// 导入实体
			sb.append("import java.util.List;" + RT_1);// 导入List
			sb.append("import com.entor.dao."+cName+"Dao;" + RT_1);//导入Dao
			sb.append("import org.springframework.beans.factory.annotation.Autowired;" + RT_1);
			sb.append("import " + SERVICE_URL + parentPack + "." + cName
					+ "ServiceI;");// 
			sb.append(RT_2 + ANNOTATION);
			sb.append(RT_1 + "@Service" + RT_1);
			sb.append("public class " + cName + "ServiceImpl ");
			//sb.append("extends " + IMPL_SERVICE_NAME + "<" + cName + "> ");
			sb.append("implements " + cName + "ServiceI");
			sb.append("{");
			sb.append(RT_1+BLANK_4+" @Autowired");
			sb.append(RT_1+BLANK_4+" public "+cName+"Dao bd;");
			//find的方法
			//sb.append(RT_2+BLANK_4+" @Override");
			sb.append(RT_1+BLANK_4+" public List<"+cName+"> find("+cName+" t) {");
			sb.append(RT_1+BLANK_8+" return bd.find(t);");
			sb.append(RT_1+BLANK_4 + "}");
			//get的方法
			/*sb.append(RT_2+BLANK_4+" @Override");
			sb.append(RT_1+BLANK_4+" public "+cName+" get("+cName+" t) {");
			sb.append(RT_1+BLANK_8+" return bd.get(t)");
			sb.append(RT_1+BLANK_4 + "}");*/
			//insert的方法
			//sb.append(RT_2+BLANK_4+" @Override");
			sb.append(RT_1+BLANK_4+" public int insert("+cName+" t) {");
			sb.append(RT_1+BLANK_8+" return bd.insert(t);");
			sb.append(RT_1+BLANK_4 + "}");
			//update的方法
			//sb.append(RT_2+BLANK_4+" @Override");
			sb.append(RT_1+BLANK_4+" public int update("+cName+" t) {");
			sb.append(RT_1+BLANK_8+" return bd.update(t);");
			sb.append(RT_1+BLANK_4 + "}");
			//delete的方法
			//sb.append(RT_2+BLANK_4+" @Override");
			sb.append(RT_1+BLANK_4+" public int delete(String id) {");
			sb.append(RT_1+BLANK_8+" return bd.delete(id);");
			sb.append(RT_1+BLANK_4 + "}");
			sb.append(RT_2 + "}");
			FileWriter fw = new FileWriter(f, false);
			fw.write(sb.toString());
			fw.flush();
			fw.close();
			printLog(fileName);
		}

	}
	//打印成功日志
	public static void printLog(String info) {
		if (PRINT_INFO_FLAG) {
			System.out.println("generate file" + info + " success");
		}
	}
	//打印错误日志
	public static void printError(String info, Exception e) {
		if (PRINT_ERROR_FLAG) {
			System.err.println("generate file" + info + " error Exception:"
					+ e.getMessage());
			e.printStackTrace();
		}
	}
}
